package com.shopng.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shopng.model.User;

import io.swagger.annotations.Api;

@Api(tags = { "Hello" })
@Controller
public class HelloController
{
  @RequestMapping("/home")
  public String home()
  {
    return "home";
  }
  
  @RequestMapping("/hello")
  public String hello()
  {
    SecurityContext ctx = SecurityContextHolder.getContext();
    Authentication auth = ctx.getAuthentication();
    if (auth.getPrincipal() instanceof UserDetails)
    {
      User user = (User) auth.getPrincipal();
      System.out.println(user.getEmail());
    }
    // 本段代码演示如何获取登录的用户资料
    return "hello";
  }
  
  @RequestMapping(value = "/first", method = RequestMethod.GET)
  @ResponseBody
  public Map<String, Object> firstResp (HttpServletRequest request){
      Map<String, Object> map = new HashMap<>();
      request.getSession().setAttribute("request Url", request.getRequestURL());
      map.put("request Url", request.getRequestURL());
      return map;
  }

  @RequestMapping(value = "/sessions", method = RequestMethod.GET)
  @ResponseBody
  public Object sessions (HttpServletRequest request){
      Map<String, Object> map = new HashMap<>();
      map.put("sessionId", request.getSession().getId());
      map.put("message", request.getSession().getAttribute("map"));
      return map;
  }
}
